﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.Mvc;
namespace Web.Core.Helper
{
    /// <summary>
    /// 前台通用类
    /// </summary>
    public partial class UIHelper
    {

        private string _PageUrl;
        private string _UpdateTargetId;
        private NameValueCollection _AddParameters;
        private NameValueCollection _QueryString
        {
            get
            {
                string queryString = new Uri(_PageUrl).Query;
                NameValueCollection coll = new NameValueCollection();
                if (queryString.IndexOf('?') == -1)
                {
                    return coll;
                }
                queryString = queryString.Substring(1);

                foreach (var str in queryString.Split('&'))
                {
                    string[] _strs = str.Split('=');
                    if (_strs.Length == 2)
                    {
                        coll.Add(_strs[0], _strs[1]);
                    }
                }
                return coll;
            }
        }

        private string _AbsolutePath
        {
            get
            {
                //  return new Uri(_PageUrl).GetLeftPart(UriPartial.Path);
                return new System.Uri(_PageUrl).AbsolutePath;
            }
        }

        public UIHelper(string currentUrl)
        {
            _PageUrl = currentUrl;
        }

        public UIHelper(string currentUrl, string UpdateTargetId)
        {
            _PageUrl = currentUrl;
            _UpdateTargetId = UpdateTargetId;
        }

        public UIHelper(string currentUrl, NameValueCollection addParameters)
        {
            _PageUrl = currentUrl;
            _AddParameters = addParameters;
        }

        public UIHelper(string currentUrl, string UpdateTargetId, NameValueCollection addParameters)
        {
            _PageUrl = currentUrl;
            _UpdateTargetId = UpdateTargetId;
            _AddParameters = addParameters;
        }

        #region GetPage得到分页的ＨＴＭＬ代码块
        /// <summary>
        /// 获取分页HTML
        /// </summary>
        /// <param name="pageIndex">当前页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="count">总数</param>
        /// <returns>分页HTML</returns>
        public string GetPage(int pageIndex, int pageSize, int count)
        {
            return GetPage(pageIndex, pageSize, count, 0, null, null, null, true, false);
        }

        public string GetPage(int pageIndex, int pageSize, int count, bool isDisplayCompletePage)
        {
            return GetPage(pageIndex, pageSize, count, 0, null, null, null, isDisplayCompletePage, false);
        }

        public string GetPage(int pageIndex, int pageSize, int count, bool isDisplayCompletePage, bool isAppend)
        {
            return GetPage(pageIndex, pageSize, count, 0, null, null, null, isDisplayCompletePage, isAppend);
        }

        /// <summary>
        /// 获取分页HTML(MVC路由的）
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="action"></param>
        /// <param name="controller"></param>
        /// <returns></returns>
        public string GetPage(int pageIndex, int pageSize, int count, UrlHelper url, string action, string controller)
        {
            return GetPage(pageIndex, pageSize, count, 0, url, action, controller, true, false);
        }

        public string GetPage(int pageIndex, int pageSize, int count, UrlHelper url, string action, string controller, bool isDisplayCompletePage)
        {
            return GetPage(pageIndex, pageSize, count, 0, url, action, controller, isDisplayCompletePage, false);
        }

        /// <summary>
        /// 获取分页HTML
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="limitMaxPages"></param>
        /// <returns></returns>
        public string GetPage(int pageIndex, int pageSize, int count, int limitMaxPages)
        {
            return GetPage(pageIndex, pageSize, count, limitMaxPages, null, null, null, true, false);
        }

        public string GetPage(int pageIndex, int pageSize, int count, int limitMaxPages, bool isDisplayCompletePage)
        {
            return GetPage(pageIndex, pageSize, count, limitMaxPages, null, null, null, isDisplayCompletePage, false);
        }

        public string GetPage(int pageIndex, int pageSize, int count, int limitMaxPages, UrlHelper url, string action, string controller)
        {
            return GetPage(pageIndex, pageSize, count, limitMaxPages, url, action, controller, true, false);
        }
        /// <summary>
        /// 获取分页HTML(MVC路由的）
        /// </summary>
        /// <param name="pageIndex">当前页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="count">总数</param>
        /// <param name="limitMaxPages">限制显示页数</param>
        /// <returns>分页HTML</returns>
        public string GetPage(int pageIndex, int pageSize, int count, int limitMaxPages, UrlHelper url, string action, string controller, bool isDisplayCompletePage, bool isAppend)
        {
            //当前页,前面和后面显示的页数
            int showNum = 2;
            //最前面和最后面显示的页数
            int lastNum = 2;

            string endHtml = "";

            //总页数
            int totalPage = (int)Math.Ceiling((double)((double)count / (double)pageSize));
            if (totalPage < 1) return "";

            if (isDisplayCompletePage)
            {
                if (limitMaxPages != 0)
                {
                    if (totalPage > limitMaxPages) totalPage = limitMaxPages;
                    endHtml = string.Format("&nbsp;&nbsp;共{0}页", totalPage);
                }
                else
                {
                    endHtml = string.Format("&nbsp;&nbsp;{1}/{2}&nbsp;&nbsp;共{0}条", count, pageIndex, totalPage);
                }
            }

            if (pageIndex <= 0) pageIndex = 1;
            if (pageIndex > totalPage) pageIndex = totalPage;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (isAppend)
            {
                if (pageIndex < totalPage && totalPage > 1)
                {
                    if (isAppend)
                    {
                        if (pageIndex < totalPage && totalPage > 1)
                        {
                            sb.Append("<div style='margin-top: -1px;background-color: #F4F4F4;border-top: 1px solid #D4D4D4;height: 36px;    line-height: 36px;text-align: center;padding: 0; color: #666666;font-size: 12px;'>");
                            if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                            {

                                sb.Append(GetTagLink(pageIndex + 1, "点击查看更多"));
                            }
                            else
                            {
                                sb.Append(GetTagLink(pageIndex + 1, "点击查看更多", url, action, controller));

                            }
                            sb.Append("</div>");
                        }
                    }
                }
            }
            else
            {
                sb.Append("<style type='text/css'>.page_Standard { padding:15px; margin:0px; text-align:center; font-family:0px; font-family:Arial; font-size:12px; }.page_Standard a{ border:#eee 1px solid; padding:2px 5px; margin:2px; color:#036cb4; text-decoration:none;}.page_Standard A:hover { border:#999 1px solid; color:#666; }.page_Standard A:active { border: #999 1px solid; COLOR: #666;}.page_Standard span { border: #036cb4 1px solid; padding:2px 5px; font-weight:bold; margin:2px; color:#fff; background:#036cb4;}.page_Standard .disabled { border:#eee 1px solid; padding:2px 5px; margin:2px; color: #ddd; }</style>");

                sb.Append("<div style='clear:both'></div><div class=\"page_Standard\" style=\"padding-bottom:15px;\">");
                int startNum = 0;
                int endNum = 0;

                startNum = pageSize * (pageIndex - 1) + 1;
                if (totalPage == pageIndex)
                {
                    endNum = count;
                }
                else
                {
                    endNum = pageSize * pageIndex;
                }
                if (isDisplayCompletePage)
                {
                    //前半部分
                    if (pageIndex > 1)
                    {
                        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                        {
                            sb.Append(GetTagLink(1, "首页"));
                            sb.Append(GetTagLink(pageIndex - 1, "上一页"));
                        }
                        else
                        {
                            sb.Append(GetTagLink(1, "首页", url, action, controller));
                            sb.Append(GetTagLink(pageIndex - 1, "上一页", url, action, controller));
                        }
                    }
                }

                if (pageIndex <= showNum + lastNum + 1)
                {
                    for (int i = 1; i < pageIndex; i++)
                    {
                        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                        {
                            sb.AppendFormat(GetTagLink(i, i.ToString()));
                        }
                        else
                        {
                            sb.AppendFormat(GetTagLink(i, i.ToString(), url, action, controller));
                        }
                    }
                }
                else
                {
                    for (int i = 1; i <= lastNum; i++)
                    {
                        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                        {
                            sb.AppendFormat(GetTagLink(i, i.ToString()));
                        }
                        else
                        {
                            sb.AppendFormat(GetTagLink(i, i.ToString(), url, action, controller));
                        }
                    }

                    sb.Append("…");

                    for (int i = pageIndex - showNum; i < pageIndex; i++)
                    {
                        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                        {
                            sb.AppendFormat(GetTagLink(i, i.ToString()));
                        }
                        else
                        {
                            sb.AppendFormat(GetTagLink(i, i.ToString(), url, action, controller));
                        }
                    }
                }

                //当前页
                if (!(pageIndex == 1 && totalPage == 1)) sb.Append("<span>" + pageIndex.ToString() + "</span>");

                //后半部分
                for (int i = pageIndex + 1; i <= pageIndex + showNum && i <= totalPage; i++)
                {
                    if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                    {
                        sb.Append(GetTagLink(i, i.ToString()));
                    }
                    else
                    {
                        sb.Append(GetTagLink(i, i.ToString(), url, action, controller));
                    }
                }

                if (pageIndex + showNum + lastNum < totalPage)
                {
                    sb.Append("…");

                    for (int i = totalPage - lastNum + 1; i <= totalPage; i++)
                    {
                        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                        {
                            sb.Append(GetTagLink(i, i.ToString()));
                        }
                        else
                        {
                            sb.Append(GetTagLink(i, i.ToString(), url, action, controller));
                        }

                    }
                }
                else
                {
                    for (int i = pageIndex + showNum + 1; i <= totalPage; i++)
                    {
                        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                        {
                            sb.Append(GetTagLink(i, i.ToString()));
                        }
                        else
                        {
                            sb.Append(GetTagLink(i, i.ToString(), url, action, controller));
                        }
                    }
                }
                if (isDisplayCompletePage)
                {
                    if (pageIndex < totalPage)
                    {
                        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller))
                        {
                            sb.Append(GetTagLink(pageIndex + 1, "下一页"));
                            sb.Append(GetTagLink(totalPage, "尾页"));
                        }
                        else
                        {
                            sb.Append(GetTagLink(pageIndex + 1, "下一页", url, action, controller));
                            sb.Append(GetTagLink(totalPage, "尾页", url, action, controller));
                        }
                    }
                }
                sb.Append(endHtml);
                sb.Append("</div>");
            }
            return sb.ToString();
        }
        #endregion

        #region GetTagLink分页页码的链接代码块
        private string GetTagLink(int pageIndex, string text, LinkType linkType)
        {
            switch (linkType)
            {
                case LinkType.Previouse:
                    return GetTagLink(pageIndex, text, "pr");
                case LinkType.Number:
                    return GetTagLink(pageIndex, text, "nu");
                case LinkType.Next:
                    return GetTagLink(pageIndex, text, "ne");
                case LinkType.First:
                    return GetTagLink(pageIndex, text, "fi");
                case LinkType.End:
                    return GetTagLink(pageIndex, text, "en");
                case LinkType.Ellipsis:
                    return GetTagLink(pageIndex, text, "el");
                default:
                    return GetTagLink(pageIndex, text, "");
            }
        }

        /// <summary>
        /// 获取分页用的连接(不带样式)
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="text">显示文字</param>
        /// <returns></returns>
        private string GetTagLink(int pageIndex, string text)
        {
            if (string.IsNullOrEmpty(_UpdateTargetId))
            {
                return "<a href=\"" + GetUrlWithPageArg(pageIndex) + "\">" + text + "</a>";
            }
            return "<a href=\"" + GetUrlWithPageArg(pageIndex) + "\" onclick=\"$('#" + _UpdateTargetId + "').load($(this).attr('href'));event.returnValue=false;return false;\">" + text + "</a>";
        }
        /// <summary>
        /// 添加ＭＶＣ路由的分页
        /// 2012－10－18：修改AddParameters无效问题
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private string GetTagLink(int pageIndex, string text, UrlHelper url, string action, string controller)
        {
            if (_AddParameters != null)
            {
                foreach (var str in _AddParameters.AllKeys)
                {
                    if (url.RequestContext.RouteData.Values.ContainsKey(str))
                        url.RequestContext.RouteData.Values[str] = _AddParameters[str];
                    else
                        url.RequestContext.RouteData.Values.Add(str, _AddParameters[str]);
                }
            }
            if (string.IsNullOrEmpty(_UpdateTargetId))
            {
                return "<a href=\"" + url.Action(action, controller, new { page = pageIndex }) + "\">" + text + "</a>";
            }
            return "<a href=\"" + url.Action(action, controller, new { page = pageIndex }) + "\" onclick=\"$('#" + _UpdateTargetId + "').load($(this).attr('href'));event.returnValue=false;return false;\">" + text + "</a>";
        }


        /// <summary>
        /// 获取分页用的连接(带样式)
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="text">显示文字</param>
        /// <param name="className">样式</param>
        /// <returns></returns>
        private string GetTagLink(int pageIndex, string text, string className)
        {
            if (string.IsNullOrEmpty(_UpdateTargetId))
            {
                return "<a class=\"" + className + "\"" + "href=\"" + GetUrlWithPageArg(pageIndex) + "\">" + text + "</a>";
            }
            return "<a class=\"" + className + "\"" + " href=\"" + GetUrlWithPageArg(pageIndex) + "\" onclick=\"$('#" + _UpdateTargetId + "').load($(this).attr('href'));event.returnValue=false;return false;\">" + text + "</a>";
        }

        /// <summary>
        /// 添加ＭＶＣ路由的分页
        /// 2012－10－18：修改AddParameters无效问题
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="text"></param>
        /// <param name="className"></param>
        /// <param name="action"></param>
        /// <param name="controller"></param>
        /// <returns></returns>
        private string GetTagLink(int pageIndex, string text, string className, UrlHelper url, string action, string controller)
        {

            if (_AddParameters != null)
            {
                foreach (var str in _AddParameters.AllKeys)
                {
                    if (url.RequestContext.RouteData.Values.ContainsKey(str))
                        url.RequestContext.RouteData.Values[str] = _AddParameters[str];
                    else
                        url.RequestContext.RouteData.Values.Add(str, _AddParameters[str]);
                }
            }


            if (string.IsNullOrEmpty(_UpdateTargetId))
            {

                return "<a class=\"" + className + "\"" + "href=\"" + url.Action(action, controller, new { page = pageIndex }) + "\">" + text + "</a>";
            }
            return "<a class=\"" + className + "\"" + " href=\"" + url.Action(action, controller, new { page = pageIndex }) + "\" onclick=\"$('#" + _UpdateTargetId + "').load($(this).attr('href'));event.returnValue=false;return false;\">" + text + "</a>";
        }
        #endregion



        public enum LinkType
        {
            /// <summary>
            /// 第一页
            /// </summary>
            First,
            /// <summary>
            /// 前一页
            /// </summary>
            Previouse,
            /// <summary>
            /// 下一页
            /// </summary>
            Next,
            /// <summary>
            /// 最后一页
            /// </summary>
            End,
            /// <summary>
            /// 数字
            /// </summary>
            Number,
            /// <summary>
            /// 省略号
            /// </summary>
            Ellipsis
        }

        public string GetUrlWithArgument(string argName, string argValue)
        {
            if (string.IsNullOrEmpty(argValue)) return GetUrlWithOutArgument(argName);

            string returnValue = "";
            StringBuilder sb = new StringBuilder();
            foreach (var str in _QueryString.AllKeys)
            {
                if (str != "page" && str != argName)
                {
                    sb.Append("&" + str + "=" + _QueryString[str]);
                }
            }
            returnValue = _AbsolutePath + "?" + argName + "=" + argValue + sb.ToString();
            return returnValue;
        }

        public string GetUrlWithArgument(NameValueCollection coll)
        {
            StringBuilder sb = new StringBuilder();
            string symbol = "?";
            foreach (string str in coll.AllKeys)
            {
                sb.Append(symbol + str + "=" + coll[str]);
                symbol = "&";
            }
            StringBuilder sb2 = new StringBuilder();
            foreach (string str in _QueryString.AllKeys)
            {
                if (str != "page" && !coll.AllKeys.Contains(str))
                {
                    sb2.Append("&" + str + "=" + _QueryString[str]);
                }
            }

            return _AbsolutePath + sb.ToString() + sb2.ToString();
        }

        public string SetUrlArgument(NameValueCollection coll)
        {
            StringBuilder sb = new StringBuilder();
            NameValueCollection myColl = new NameValueCollection(coll);
            foreach (string str in _QueryString.AllKeys)
            {
                if (myColl.AllKeys.Contains(str) == false)
                {
                    myColl.Add(str, _QueryString[str]);
                }
            }
            //myColl.Add(_QueryString);
            string symbol = "?";
            foreach (string str in myColl.AllKeys)
            {
                if (!string.IsNullOrEmpty(myColl[str]))
                {
                    sb.Append(symbol + str + "=" + HttpContext.Current.Server.UrlEncode(myColl[str]));
                    symbol = "&";
                }
            }

            return _AbsolutePath + sb.ToString();
        }

        public string GetUrlWithOutArgument(string argName)
        {
            string returnValue = "";
            StringBuilder sb = new StringBuilder();
            foreach (var str in _QueryString.AllKeys)
            {
                if (str != "page" && str != argName)
                {
                    sb.Append("&" + str + "=" + _QueryString[str]);
                }
            }
            if (sb.Length > 0)
            {
                returnValue = _AbsolutePath + "?" + sb.ToString().Substring(1);
            }
            else
            {
                returnValue = _AbsolutePath;
            }

            return returnValue;
        }

        public string GetUrlWithOutArgument(string[] argName)
        {
            string returnValue = "";
            StringBuilder sb = new StringBuilder();
            foreach (var str in _QueryString.AllKeys)
            {
                if (str != "page" && !argName.Contains(str))
                {
                    sb.Append("&" + str + "=" + _QueryString[str]);
                }
            }
            if (sb.Length > 0)
            {
                returnValue = _AbsolutePath + "?" + sb.ToString().Substring(1);
            }
            else
            {
                returnValue = _AbsolutePath;
            }

            return returnValue;
        }

        private string GetUrlWithPageArg(int pageIndex)
        {
            string returnValue = "";
            NameValueCollection coll = _QueryString;
            if (_AddParameters != null)
            {
                foreach (var str in _AddParameters.AllKeys)
                {
                    if (_QueryString.AllKeys.Contains(str))
                    {
                        coll[str] = HttpContext.Current.Server.UrlEncode(_AddParameters[str]);
                    }
                    else
                    {
                        coll.Add(str, HttpContext.Current.Server.UrlEncode(_AddParameters[str]));
                    }
                }
            }

            StringBuilder sb = new StringBuilder();
            foreach (var str in coll.AllKeys)
            {
                if (str != "page")
                {
                    sb.Append("&" + str + "=" + coll[str]);
                }
            }
            if (sb.Length > 0)
            {
                sb.Append("&page=" + pageIndex.ToString());
                returnValue = _AbsolutePath + "?" + sb.ToString().Substring(1);
            }
            else
            {
                sb.Append("?page=" + pageIndex.ToString());
                returnValue = _AbsolutePath + sb.ToString();
            }

            return returnValue;
        }

        private NameValueCollection ConvertToNameValueCollection(string queryString)
        {
            NameValueCollection coll = new NameValueCollection();
            if (queryString.IndexOf('?') == -1)
            {
                return coll;
            }
            queryString = queryString.Substring(1);

            foreach (var str in queryString.Split('&'))
            {
                string[] _strs = str.Split('=');
                coll.Add(_strs[0], _strs[1]);
            }
            return coll;
        }

    }


}
